package xin.marcher.wind.process.instance;

import org.springframework.beans.BeansException;
import org.springframework.stereotype.Component;
import xin.marcher.wind.process.model.ProcessContextFactory;
import xin.marcher.wind.process.processor.Processor;

/**
 * @author marcher
 */
@Component
public class SpringBeanInstanceCreator implements ProcessorInstanceCreator {

    @Override
    public Processor newInstance(String className, String name) throws Exception {
        Object bean;
        try {
            // 根据流程节点的 class，去 spring 容器里寻找这个 class 对应的一个 bean
            Class<?> clazz = Class.forName(className);
            bean = SpringUtil.getBean(clazz);
        } catch (BeansException e) {
            return ProcessContextFactory.DEFAULT_INSTANCE_CREATOR.newInstance(className, name);
        }

        if (!(bean instanceof Processor)) {
            throw new IllegalArgumentException("类 " + className + " 不是 Processor 实例");
        }
        // 接口类型的强转，所有的流程节点都是实现了 Processor 接口的
        Processor processor = (Processor) bean;
        // 拿出来的每个流程节点的 bean 实例，都可以强转为 Processor 接口类型，设置进去流程节点对应的 name 就可以了
        processor.setName(name);
        return (Processor) bean;
    }
}
